package com.hm.hall.commons.service;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.hm.hall.commons.util.ActionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class JpushService {

    static Logger log = Logger.getLogger(JpushService.class);

    //	static String appKey = "265a4a53134d116ac23fc68c";
//	static String masterSecret = "0196e6e1c5231c1dd89a8d03";
    static String appKey = "2625a8bc3948a56431f83acf";
    static String masterSecret = "7c6d5c3accbcaf3097bde450";
    static String appKey2 = "47708d815175050c1e5d70a6"; //pro
    static String masterSecret2 = "2a7f61d9f158ade3497b9e0b"; //pro

    private static Boolean flag = null;

    public static void main(String[] args) {
//		pushToAll("这是一条推送全平台全部用户信息","这是标题","这是一条推送全平台全部用户信息");
//		pushToAndroidAll("这是一条推送安卓全部用户信息","hall测试");
//		pushToIosAll("这是一条推送苹果全部用户信息这是一条推送安卓全部用户信息,这是一条推送安卓全部用户信息这是一条推送安卓全部用户信息,这是一条推送安卓全部用户信息这是一条推送苹果全部用户信息这是一条推送安卓全部用户信息,这是一条推送安卓全部用户信息这是一条推送安卓全部用户信息,这是一条推送安卓全部用户信息");
        pushToAlias("这是一条推送60000004用户信息", "这是一条推送60000004用户信息", "这是一条推送60000004用户信息", "60000004");
    }


    private static Boolean getFlag() {
        if (flag == null) {
            flag = ActionUtils.isIdcEnv();
        }
        return flag;
    }

    /**
     * 推送所有用户
     *
     * @param androidTitle
     * @param androidText
     * @param iosText
     */
    public static void pushToAll(String androidTitle, String androidText, String iosText) {
        PushPayload payload = buildPushObjectAll(androidTitle, androidText, iosText);
        push(payload);
    }

    /**
     * 推送ios所有用户
     *
     * @param iosText
     */
    public static void pushToIosAll(String iosText) {
        PushPayload payload = buildPushObjectIosAll(iosText);
        push(payload);
    }

    /**
     * 推送安卓所有用户
     *
     * @param androidText
     * @param androidTitle
     */
    public static void pushToAndroidAll(String androidText, String androidTitle) {
        PushPayload payload = buildPushObjectAndroidAll(androidText, androidTitle);
        push(payload);
    }

    /**
     * 推送给用户别名 （用户ID）
     *
     * @param androidText
     * @param androidTitle
     * @param iosText
     * @param userId
     */
    public static void pushToAlias(String androidText, String androidTitle, String iosText, String userId) {
        log.info("jpush->" + userId);
        PushPayload payload = buildPushObjectToAlias(androidText, androidTitle, iosText, userId);
        push(payload);
    }

    private static void push(PushPayload payload) {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.info("Got result - " + result);

        } catch (APIConnectionException e) {
            log.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
        push2(payload);//向pro发送jpush
    }

    private static void push2(PushPayload payload) {
        JPushClient jpushClient = new JPushClient(masterSecret2, appKey2);
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.info("Got result - " + result);

        } catch (APIConnectionException e) {
            log.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
    }

    private static PushPayload buildPushObjectToAlias(String androidText, String androidTitle, String iosText, String userId) {
        Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.all());
        builder.setAudience(Audience.alias(userId));
        builder.setOptions(Options.newBuilder()
                .setApnsProduction(getFlag())
                .build());
        cn.jpush.api.push.model.notification.Notification.Builder nBuilder = Notification.newBuilder();
        nBuilder.addPlatformNotification(IosNotification.newBuilder()
                .autoBadge()
                .setAlert(iosText)
                .setSound("default")
                .build());
        nBuilder.addPlatformNotification(AndroidNotification.newBuilder()
                .setAlert(androidText)
                .setTitle(androidTitle)
                .build());
        builder.setNotification(nBuilder.build());
        return builder.build();
    }

    private static PushPayload buildPushObjectAll(String androidTitle, String androidText, String iosText) {
        Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.all());
        builder.setAudience(Audience.all());
        builder.setOptions(Options.newBuilder()
                .setApnsProduction(getFlag())
                .build());
        cn.jpush.api.push.model.notification.Notification.Builder nBuilder = Notification.newBuilder();
        nBuilder.addPlatformNotification(IosNotification.newBuilder()
                .autoBadge()
                .setAlert(iosText)
                .build());
        nBuilder.addPlatformNotification(AndroidNotification.newBuilder()
                .setAlert(androidText)
                .setTitle(androidTitle)
                .build());
        builder.setNotification(nBuilder.build());
        return builder.build();
    }

    private static PushPayload buildPushObjectAndroidAll(String text, String title) {
        Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.android());
        builder.setAudience(Audience.all());
        builder.setNotification(Notification.android(text, title, null));

        return builder.build();
    }

    private static PushPayload buildPushObjectIosAll(String text) {
        Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.ios());
        builder.setAudience(Audience.all());
        builder.setOptions(Options.newBuilder()
                .setApnsProduction(getFlag())
                .build());
        Notification.ios_auto_badge();
        builder.setNotification(Notification.alert(text));
        return builder.build();
    }

    private void bossPushMessage(String androidTitle, String androidText, String iosText, String userIdList, String platform, String sendTime,
                                 String timeToLive) {
        if (StringUtils.isEmpty(userIdList)) {
            if (platform.equals("ALL")) {
                //	pushToAll(text);
                JpushService.pushToAll(androidTitle, androidText, iosText);
            } else if (platform.equals("IOS")) {
                JpushService.pushToIosAll(iosText);
            } else {
                JpushService.pushToAndroidAll(androidText, androidTitle);
            }
        } else {
            String[] userIds = userIdList.split(",");
            for (String userId : userIds) {
                JpushService.pushToAlias(androidText, androidTitle, iosText, userId);
            }
        }
    }
}
